<?php

global $cachefile; 

    $cachefilename = urlencode($_SERVER['REQUEST_URI'])."-".md5($_SERVER['REQUEST_URI']); 

    $cachefile = sys_get_temp_dir ().DIRECTORY_SEPARATOR.$cachefilename.'.cache'; 

    // How long to keep cache file? 
    $cachetime = 5;    //5sec 

    // Is cache file still fresh? If so, serve it.    
    if (file_exists($cachefile) && time() - $cachetime < filemtime($cachefile)) { 
      readfile($cachefile); 
      exit; 
    } 

    function cacheOutputtoFile() 
    { 
        global $cachefile; 
        $webpage = ob_get_contents(); 
        if ($fp = fopen($cachefile, 'w+')) 
        { 
            if (flock($fp, LOCK_EX)) 
            { // do an exclusive lock 
                ftruncate($fp, 0); // truncate file 
                //compress unnecesary spaces 
                $busca = array('/\>[^\S ]+/s','/[^\S ]+\</s','/(\s)+/s'); 
                $reemplaza = array('>','<','\\1'); 
                $webpage = preg_replace($busca, $reemplaza, $webpage); 
                
                fwrite($fp, $webpage); 
                fclose($fp); 
            } 
        } 
        echo $webpage; 
    } 

    ob_start(); 
    register_shutdown_function("cacheOutputtoFile"); 

//note you must use register_shutdown_function instead of using "cacheOutputtoFile" as parameter of ob_start as socket is already closed when callback function is called, then the client not get the echo $webpage output. 
?> 
